package com.yunhe.common.filter;


import com.yunhe.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>Description: </p>
 *
 */

public class ServerContextFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(ServerContextFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {


        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String projectCode = httpServletRequest.getHeader(ServerContext.PROJECT_CODE);
        if(StringUtil.isEmpty(projectCode)){
            projectCode = httpServletRequest.getParameter(ServerContext.PROJECT_CODE);
        }
        if (projectCode != null) {
            logger.info("=== === [dofilter] projectCode is :{}",projectCode);
        }


        // 如果这里仍然为空，那么不做处理
        ServerContextHolder.getContext().setProjectCode(projectCode);

        /*****************token设置******************/
        String accessToken = httpServletRequest.getHeader("Access-Token");
        if(StringUtil.isEmpty(accessToken)){
            accessToken = httpServletRequest.getParameter("Access-Token");

        }
        if (accessToken != null) {
            logger.info("[Access-Token is ]:{}", accessToken);
            logger.info("[Request URL is ]:{}", httpServletRequest.getRequestURL());
        }
        filterChain.doFilter(httpServletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}
}
